<template>
  <el-menu
    :default-active="activeMenu"
    :ellipsis="false"
    class="el-menu-demo"
    mode="horizontal"
    @select="handleMenuSelect"
  >
    <!-- <el-menu-item index="">All Categories</el-menu-item> -->
    <el-menu-item index="frontend">Frontend</el-menu-item>
    <el-menu-item index="backend">Backend</el-menu-item>
    <el-menu-item index="fullstack">Fullstack</el-menu-item>
    <el-menu-item index="mobile">Mobile</el-menu-item>
    <el-menu-item index="knowledge">知识点</el-menu-item>
  </el-menu>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const activeMenu = ref('')

// 初始化时设置activeMenu
onMounted(() => {
  updateActiveMenu()
})

// 监听路由变化，实时更新activeMenu
watch(
  () => route.fullPath, // 改为监听完整路径的变化，确保捕捉所有路由变化
  () => {
    updateActiveMenu()
  }
)

const updateActiveMenu = () => {
  nextTick(() => {
    activeMenu.value =
      route.name === 'KnowledgeList' ? 'knowledge' : (route.query.category as string) || ''
  })
}

// 菜单选择事件处理
const handleMenuSelect = (key: string) => {
  if (key === 'knowledge') {
    router.push({ name: 'KnowledgeList' })
  } else {
    router.push({ path: '/', query: { category: key } })
  }
}
</script>

<style scoped>
.el-menu-demo {
  border-bottom: 1px solid transparent !important;
}
</style>
